package cn.com.callback
import groovy.json.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import groovy.swing.impl.DefaultAction;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import cn.com.elite.Util;

public class syncIVRNotifiyResult implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(syncIVRNotifiyResult.class);

	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");
		log.debug("-------------------------start syncIVRNotifiyResult 开始-----------------");
		log.debug("request请求----------------:"+request);

		String getMethod = request.getMethod();
		String callJson="";
		BufferedReader iny = null;

		def reJson = "";
		def dataSourceID = "dataSource";

		log.debug("getMethod:"+getMethod);
		if (getMethod.equals("GET")) {
			callJson = request.getParameter("jsondata");
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				callJson += line;
			}
		}

		//调用存储过程处理工单
		log.debug("调用存储过程处理SQL...");
		def procedure="{call Dbo.Job_DealCallNotice(?,?,?)}";
		def inputMap = new String[2];
		inputMap[0] = "syncIVRNotifiyResult";
		inputMap[1] = "OUT";

		log.debug("调用存储过程处理SQL:" + procedure);
		def reSult = eliteBean.executeWithReturn(procedure, inputMap, 'dataSource');
		log.debug("调用存储过程处理返回:" + reSult);

		log.debug("原始Post请求参数:"+callJson);
		try {
			//解析返回Json内容
			JSONObject jsonObject = new JSONObject(callJson);

			//解析所需要的值
			String source = GetJV(jsonObject, "source");//系统来源
			String data = GetJV(jsonObject, "data");
			String pagenum = GetJV(jsonObject, "pagenum");//当前页
			String pagesize = GetJV(jsonObject, "pagesize");//每页大小
			log.debug("调用data：" + data);

			JSONArray dataArray = new JSONArray(data);
			int dataArrayLen = dataArray.length();

			log.debug("调用DataArray：" + dataArray.toString() + "DataArray Size:" + dataArrayLen);

			//处理数据
			JSONObject dataObject = null;

			def ncid = '';//序号，系统来源+序号全局唯一
			def tempncid = '';
			for(int i=0;i<dataArrayLen;i++) {
				dataObject = dataArray.getJSONObject(i);
				log.debug("dataObject:" +dataObject);

				tempncid = GetJV(dataObject, "ncid");

				ncid = ncid+tempncid+"','";
				log.debug("ncid:" +ncid);
			}
			def querySql0 = '';
			List list =new ArrayList();
			querySql0 = "select ncid,callstarttime,callendtime,callestablishtime,callcode,callmsg from (select a.Ncid as ncid,Convert(varchar(20),b.Callstarttime,120) as callstarttime,Convert(varchar(20),b.Callendtime,120) as callendtime,Convert(varchar(20),b.CallEstablishTime,120) as callestablishtime,b.Callresult as callcode,c.obresultdesc as callmsg,ROW_NUMBER() OVER(Order by a.Ncid ) AS RowId from IVR_CallNotice a LEFT JOIN IVR_CallNotice_Policy b on a.Rec_Guid=b.Rec_Guid left join T_Obresult c on b.Callresult=c.obresult_id where 1=1 and a.Status!=-1 and b.Callresult !=null or b.Callresult !='' and a.Ncid in ('"+ncid+"')) as a where a.RowId between ('"+pagenum+"'+0-1)*('"+pagesize+"'+0) and ('"+pagenum+"'+0)*('"+pagesize+"'+0)";
			list=eliteBean.chaxun_sql(querySql0,"dataSource");

			//获取总行数
			def listsize =list.size();
			log.debug("querySql0获取总条数:"+listsize);

			def reJoson = Util.getJsonFromList(list);
			//判断返回为空
			if(listsize==0||reJoson==null) {
				reJoson='';
			}
			reJoson= "{\"code\":\"1\",\"message\":\"处理完成!\",\"data\":"+reJoson+"}"

			log.debug("querySql0获取Json:"+reJoson);
			return reJoson;
		} catch (Exception e) {
			log.error("ErrorMessage",e);
			reJson= "{\"Code\":\"-1\",\"Message\":\"错误:"+e.getMessage()+"\"}";
			log.debug("处理异常返回Json:"+reJson);
			return reJson;
		}

	}

	public static String GetJV(JSONObject inJson, String getKey) {
		log.debug("syncIVRNotifiyCall inJson:" + inJson);
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				log.warn("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = "";
			}else {
				log.debug("GetJV 获取参数值-" + getKey + ":" + Rev_Value);
			}
		}
		return Rev_Value;
	}
}